# coding: utf8
from django.shortcuts import render
from django.http.response import HttpResponse
from utils import captcha as ch
from django.template.context_processors import csrf
from utils.captcha import CaptchaSession

# Create your views here.
def index(request):
	return render(request, 'it/base.html', {})

def get_captcha(request):
	'''生成并获取验证码'''
	url_path = request.GET.get('url_path')
	# csrf_token, django自带功能, 每台机器每个浏览器只会有一个csrf_token
	csrf_token = str(csrf(request).get('csrf_token'))
	# 拼接session key 避免数据库被撑爆
	cs = CaptchaSession()
	captcha_session_key = cs.get_captcha_session_key(url_path, csrf_token)

	captcha_buf, text = ch.get_captcha()
	request.session[captcha_session_key] = text.lower() # 存储验证码到session里
	request.session.set_expiry(60 * 30)	# 30分钟失效, 秒计算

	return HttpResponse(captcha_buf, 'image/png')